package village.rainbow.slipin.ui;

import village.rainbow.slipin.BaseActivity;
import village.rainbow.slipin.R;
import village.rainbow.slipin.adapter.ListCustomAdapter;
import village.rainbow.slipin.adapter.ListFolderAdapter;
import village.rainbow.slipin.datamodel.DataRow;
import village.rainbow.slipin.datamodel.DataRowBean;
import village.rainbow.slipin.datamodel.DataTable;
import village.rainbow.slipin.ui.carousel.UiPagingScrollView;
import village.rainbow.slipin.util.FileUtil;
import village.rainbow.slipin.util.StringUtil;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class SlipinActivity extends BaseActivity{
	
	private int BACK_MODE = 0;
	private static final int BACK_MODE_NORMAL 	= 0;
	private static final int BACK_MODE_DEL 		= 1;
	
	private ToggleButton mBtnAll;
	private ToggleButton mBtnDate;
	
	private EditText mInputSearch;
	
	private ListView mFolderList;
	private ListFolderAdapter mFolderAdapter;
	
	private ListView mDailyList;
	private ListCustomAdapter mAdapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_daily);
		
		TextView tvTitle = (TextView)findViewById(R.id.menu_title);
		tvTitle.setText("Slip in");
		
		mBtnAll = (ToggleButton)findViewById(R.id.btn_all);
		mBtnAll.setTypeface(Typeface.MONOSPACE);
		mBtnAll.setTextColor(Color.WHITE);
		mBtnAll.setTextOn("All");
		mBtnAll.setTextOff("All");
		mBtnAll.setText("All");
		mBtnAll.setOnCheckedChangeListener(mCheckedChangeListener());
		mBtnAll.setOnClickListener(this);
		
		mBtnDate = (ToggleButton)findViewById(R.id.btn_date);
		mBtnDate.setTypeface(Typeface.MONOSPACE);
		mBtnDate.setTextColor(Color.WHITE);
		
		String today = StringUtil.currentDate();
		String btnTextToday = StringUtil.currentDate("yyyy년 MM월 dd일") + "(" + StringUtil.getDayOfWeek(today) + ")";
		mBtnDate.setTextOff(btnTextToday);
		mBtnDate.setTextOn(btnTextToday);
		mBtnDate.setText(btnTextToday);
		mBtnDate.setOnCheckedChangeListener(mCheckedChangeListener());
		mBtnDate.setOnClickListener(this);
		
		mFolderList = (ListView)findViewById(R.id.list_folder);
		mFolderList.setDividerHeight(0);
		mFolderAdapter = new ListFolderAdapter(this, new DataTable(), getResizeLayout());
		mFolderList.setAdapter(mFolderAdapter);
		
		mDailyList = (ListView)findViewById(R.id.daily_list);
		mDailyList.setDividerHeight(0);		
		mAdapter = new ListCustomAdapter(this, new DataTable(), getResizeLayout() );
		mDailyList.setAdapter(mAdapter);
		
		mDailyList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				DataRow item = (DataRow) mAdapter.getItem(position);
				
				Intent i = new Intent(SlipinActivity.this, ViewSlipActivity.class);
				i.putExtra("DATA", new DataRowBean(item));
				startActivity(i);
			}
		});
		
		mDailyList.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View v, int pos, long id) {
				
				Vibrator vi = (Vibrator) SlipinActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
				vi.vibrate(100);
				
				return false;
			}
		});
		
		mInputSearch = (EditText)findViewById(R.id.input_search);
		mInputSearch.addTextChangedListener(mTextWatcher());
		
		Button btnSearch = (Button)findViewById(R.id.btn_search);		
		Button btnNew = (Button)findViewById(R.id.btn_new);
		Button btnMore = (Button)findViewById(R.id.btn_more);
		btnSearch.setOnClickListener(this);
		btnNew.setOnClickListener(this);
		btnMore.setOnClickListener(this);
		
		mBtnAll.performClick();
		
		ToggleButton toggleFolder = (ToggleButton)findViewById(R.id.btn_folder);
		toggleFolder.setChecked(false);
		toggleFolder.setTextOn("=");
		toggleFolder.setTextOff("=");
		toggleFolder.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				toggleFolder(isChecked);
			}
		});
		
		try{
			DataTable list = mDao.getFolderList();
			mFolderAdapter.clear();
			mFolderAdapter.addAll(list);
			mFolderAdapter.notifyDataSetChanged();
			mFolderAdapter.setOnClickListener(mFolderClickListener);
		}catch(Exception e){
			errorHandler(e);
		}
		
	}
	
	private OnClickListener mFolderClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// 폴더버튼 누름
			DataRow folderRow = (DataRow)v.getTag();
			String folderId = folderRow.getString("FOLDER_ID", "");
			
			// 설정버튼
			if(folderId.equals("-99")){
				Intent i = new Intent(SlipinActivity.this, FolderActivity.class);
				startActivity(i);
				return;
			}

		}
	};
	
	boolean mIsRunning = false;
	// true : 보여짐, false : 안보여짐
	private void toggleFolder(final boolean show){
		
		if (mIsRunning)
			return;
		
		mIsRunning = true;
		
		final LinearLayout layoutFolder = (LinearLayout)findViewById(R.id.layout_folder);
		Thread t = new Thread(new Runnable(){
			@Override
			public void run() {
				
				if(!show && layoutFolder.getTranslationX() <= ((int)-200*getParentRatioW()))
					return;
				if(show && layoutFolder.getTranslationX() >= 0)
					return;
				
				try {
					mIsRunning = true;
					
					int destX = show ? 0 : (int)(-200 * getParentRatioW()); 
					
					while (true) {
						
						float curX = (float)layoutFolder.getTranslationX();
						
						int xVector = 0;
						if(show){
							if(curX >= destX)
								break;
							xVector = (int)(curX + 50);
						}else{
							if(curX <= destX)
								break;
							xVector = (int)(curX - 50);
						}
						
						final int nextX = xVector;
						
						layoutFolder.post(new Runnable(){
							@Override
							public void run() {
								layoutFolder.setTranslationX(nextX);
								layoutFolder.postInvalidate();
							}
						});

						
						try {
							Thread.sleep(30);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				} finally {
					mIsRunning = false;					
				}
			}
		});
		t.start();
	}
	
	
	@Override
	public void OnSizeChangeComplete() {
		mAdapter.setResizeLayout(getResizeLayout());
		mFolderAdapter.setResizeLayout(getResizeLayout());
	}
	
	private OnCheckedChangeListener mCheckedChangeListener(){
		OnCheckedChangeListener listener = new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					buttonView.setBackgroundColor(Color.rgb(70, 230, 230));
				}else{
					buttonView.setBackgroundColor(Color.argb(50, 0, 0, 0));
				}
			}
		};
		return listener;
	}
	
	private TextWatcher mTextWatcher() {
		TextWatcher textWatcher = new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			
			@Override
			public void afterTextChanged(Editable s) {
				refreshList(s.toString());
			}
		};
		return textWatcher;
	}
	

	@Override
	public void onClick(View v) {
		super.onClick(v);
		
		int id = v.getId();
		switch(id){
			case R.id.btn_date:
				mBtnAll.setChecked(false);
				mBtnDate.setChecked(true);
				refreshList(mInputSearch.getText().toString(), StringUtil.currentDate());
				break;
			case R.id.btn_all:
				mBtnAll.setChecked(true);
				mBtnDate.setChecked(false);
				refreshList(mInputSearch.getText().toString(), "");
				break;
			case R.id.btn_new:
				Intent i = new Intent(SlipinActivity.this, MakeSlipActivity.class);
				startActivity(i);
				break;
			case R.id.btn_more:
				FileUtil.pullDbToSd(this);
				break;
			case R.id.btn_search:
				toggleSearchLayout();
				break;
		}
	}
	
	private void toggleSearchLayout() {
		LinearLayout layoutSearch = (LinearLayout)findViewById(R.id.layout_search);
		if(layoutSearch.getTag() == null || (Boolean)layoutSearch.getTag()){
			layoutSearch.setVisibility(View.VISIBLE);
			layoutSearch.setTag(false);
		}else{
			layoutSearch.setVisibility(View.GONE);
			layoutSearch.setTag(true);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		refreshList();
	}
	
	private void refreshList(){
		this.refreshList("");
	}
	
	private void refreshList(String keyword) {
		this.refreshList(keyword, "");
	}
	
	private void refreshList(final String keyword, final String date){
		runOnUiThread(new Runnable(){
			@Override
			public void run() {
				try{
					DataTable list = mDao.getDailyScene(keyword, date);
					mAdapter.clear();
					mAdapter.addAll(list);
					mAdapter.notifyDataSetChanged();
				}catch(Exception e){
					errorHandler(e);
				}		
			}
		});
	}

	@Override
	public void onBackPressed() {
		if(BACK_MODE == BACK_MODE_DEL){
			// 리스트 선택 화면을 갱신한다.
		}else{
			super.onBackPressed();	
		}
	}

	
}
